﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DAL;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Text;

namespace PeisongWeb.admin
{
    public partial class recipeEdit : adminPage
    {
        protected int id
        {
            get { int tmp; try { tmp = Convert.ToInt32(ViewState["id"]); } catch { tmp = 0; } return tmp; }
            set { ViewState["id"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            #region 数据加载
            if (hasPermission("BE", 1))
            {
                if (!IsPostBack)
                {
                    if (Request.QueryString["category"] != null)
                    {
                        if (Library.Number.IsIntPositive(Request.QueryString["category"]))
                        {
                            id = Convert.ToInt32(Request.QueryString["category"]);
                        }
                    }

                    drpBind();

                    if (id != 0)
                    {
                        getDetails();
                        if (!string.IsNullOrEmpty(Request.QueryString["action"]))
                        {
                            switch (Request.QueryString["action"])
                            {
                                case "view": btn_Save.Text = "保存为系统菜谱"; break;
                                case "edit": btn_Save.Text = "保存"; break;
                            }
                        }
                    }
                    else
                    {
                    }
                }
                BindSelectedProduct();
            }
            else
            {
                Library.Script.ClientMsgUrl("没有权限！", "index.aspx");
                return;
            }
            #endregion
        }
        #region 绑定初始化数据
        protected void BindSelectedProduct()
        {
            if (!string.IsNullOrEmpty(hdProductSotre.Value))
            {
                List<ProductItem> selectedProduct = JsonConvert.DeserializeObject<List<ProductItem>>(hdProductSotre.Value);
                rptSelectedProduct.DataSource = selectedProduct;
                rptSelectedProduct.DataBind();
            }
        }
        private void getDetails()
        {
            RecipeEntity category = logic.recipe.getById(id);
            txt_Name.Text = category.Name;
            txt_Sort.Text = category.Sort.ToString();
            drp_ParentCategory.SelectedIndex = drp_ParentCategory.Items.IndexOf(drp_ParentCategory.Items.FindByValue(category.Rcid.ToString()));
            chx_isShow.Checked = category.IsShow;
            hdCurrentSource.Value = category.Source;
            hdCurrentDishName.Value = category.Name;
            chkRecommend.Checked = category.IsRecommend;
            txtDescrption.Text = category.Description;
            DataTable dt = logic.recipeItem.listRecipeItemByRecipeId(id);
            List<ProductItem> recipeItems = new List<ProductItem>();

            foreach (DataRow row in dt.Rows)
            {
                ProductItem product = new ProductItem() { ProductId = Convert.ToInt32(row["productId"]), ProductName = row["name"].ToString() };
                recipeItems.Add(product);
            }

            hdProductSotre.Value = JsonConvert.SerializeObject(recipeItems);
        }
        #endregion

        #region 弹出窗口数据 绑定

        private void drpBind()
        {
            drp_ParentCategory.DataSource = logic.recipeCategory.select("treelevel=0", "rcid", 1000, 1).Tables[1];
            drp_ParentCategory.DataBind();
            drp_ParentCategory.Items.Insert(0, new ListItem("--无--", "0"));
        }
        void categoryRootBind()
        {
            ddl_CategoryRoot.DataSource = logic.category.getByParent(0);
            ddl_CategoryRoot.DataBind();
            ddl_CategoryRoot.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
        }

        void categorySubBind()
        {
            //当大类不等于空的时候，就绑定小类
            if (ddl_CategoryRoot.SelectedValue != "")
            {
                DataTable dt = logic.category.getByParent(Convert.ToInt32(ddl_CategoryRoot.SelectedValue));
                ddl_CategorySub.DataSource = dt;
                ddl_CategorySub.DataBind();
                ddl_CategorySub.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
            }
            else
            {
                ddl_CategorySub.Items.Clear();
                ddl_CategorySub.Items.Insert(0, new System.Web.UI.WebControls.ListItem("--请选择--", ""));
            }
        }
        protected void ddl_CategoryRoot_SelectedIndexChanged(object sender, EventArgs e)
        {
            categorySubBind();
        }
        protected void BindAllProducts()
        {
            StringBuilder where = new StringBuilder();
            where.Append(" 1=1");

            if (!string.IsNullOrEmpty(ddl_CategorySub.SelectedValue))
                where.AppendFormat(" and categoryId={0}", ddl_CategorySub.SelectedValue);
            if (txt_ProductNo.Text.Trim() != "")
                where.AppendFormat(" and productNo='{0}'", txt_ProductNo.Text.Trim());
            if (txt_ProductName.Text.Trim() != "")
                where.AppendFormat(" and [name] like '%{0}%'", txt_ProductName.Text.Trim());

            DataSet ds = logic.product.select(where.ToString(), "productId", AspNetPager1.PageSize, AspNetPager1.CurrentPageIndex);
            AspNetPager1.RecordCount = Convert.ToInt32(ds.Tables[0].Rows[0][0]);

            rpt_Products.DataSource = ds.Tables[1];
            rpt_Products.DataBind();


        }
        // 搜索
        protected void lbn_search_Click(object sender, EventArgs e)
        {
            BindAllProducts();
        }
        // 重置
        protected void lbn_reset_Click(object sender, EventArgs e)
        {
            BindAllProducts();
        }
        // 添加到菜谱
        protected void lbn_AddTo_Click(object sender, EventArgs e)
        {
            List<ProductItem> selectedProduct = null;
            if (!string.IsNullOrEmpty(hdProductSotre.Value))
            {
                selectedProduct = JsonConvert.DeserializeObject<List<ProductItem>>(hdProductSotre.Value);
            }
            else
            {
                selectedProduct = new List<ProductItem>();
            }

            foreach (RepeaterItem item in rpt_Products.Items)
            {
                if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
                {
                    CheckBox chk = item.FindControl("cbx_isSelect") as CheckBox;

                    if (chk != null && chk.Checked)
                    {
                        ProductItem product = new ProductItem();
                        product.ProductId = Convert.ToInt32(chk.Attributes["ProductId"]);
                        product.ProductName = chk.Attributes["Name"];

                        // 匿名方法查找
                        //ProductItem current = selectedProduct.Find(delegate(ProductItem productItem) { return productItem.ProductId == product.ProductId; });
                        // lamdba表达式
                        ProductItem current = selectedProduct.Find(productItem => productItem.ProductId == product.ProductId);
                        if (current == null)
                        {
                            selectedProduct.Add(product);
                        }
                    }
                }
            }

            hdProductSotre.Value = JsonConvert.SerializeObject(selectedProduct);
            BindSelectedProduct();
        }
        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindAllProducts();
        }

        #endregion

        // 添加原料
        protected void lbn_AddProduct_Click(object sender, CommandEventArgs e)
        {
            // 初始化数据
            txt_ProductNo.Text = txt_ProductName.Text = string.Empty;
            BindAllProducts();
            categoryRootBind();
            categorySubBind();

            ddl_CategoryRoot.SelectedValue = "";
            ddl_CategorySub.SelectedValue = "";

            win_product.Show();
        }
        protected void rptSelectedProduct_ItemCommand(object sender, RepeaterCommandEventArgs e)
        {
            #region 删除选择的原料
            if (e.CommandName == "Del")
            {
                List<ProductItem> selectedProduct = null;
                if (!string.IsNullOrEmpty(hdProductSotre.Value))
                {
                    selectedProduct = JsonConvert.DeserializeObject<List<ProductItem>>(hdProductSotre.Value);
                    int productId = 0;
                    if (e.CommandArgument != null)
                    {
                        int.TryParse(e.CommandArgument.ToString(), out productId);
                    }

                    foreach (ProductItem item in selectedProduct)
                    {
                        if (item.ProductId == productId)
                        {
                            selectedProduct.Remove(item);
                            break;
                        }
                    }
                }

                if (selectedProduct != null)
                {
                    hdProductSotre.Value = JsonConvert.SerializeObject(selectedProduct);
                }
                else
                {
                    hdProductSotre.Value = string.Empty;
                }

                BindSelectedProduct();
            }
            #endregion
        }
        protected void btn_Save_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(hdProductSotre.Value))
            {
                Library.Script.ClientMsg("请选择菜谱原料!");
                return;
            }
            if (txt_Name.Text != hdCurrentDishName.Value || (!string.IsNullOrEmpty(Request.QueryString["action"]) && Request.QueryString["action"] == "view"))
            {
                if (logic.recipe.isExistsRecipeName(0, txt_Name.Text, "1"))
                {
                    Library.Script.ClientMsg("菜谱列表中已经存在该名称!");
                    return;
                }
            }

            #region 保存菜谱信息

            RecipeEntity cat = new RecipeEntity();
            cat.Name = txt_Name.Text;
            int rcid = 0;
            int.TryParse(drp_ParentCategory.SelectedValue, out rcid);
            cat.Rcid = rcid;
            cat.Description = txtDescrption.Text;
            int sort = 0;
            int.TryParse(txt_Sort.Text, out sort);
            cat.Sort = sort;
            cat.Source = "1";
            cat.IsShow = chx_isShow.Checked;
            cat.IsRecommend = chkRecommend.Checked;
            cat.Favorite = false;
            cat.CompanyId = 0;// 系统录入由CompanyId和Source两个条件决定

            if (id != 0)
            {
                cat.RecipeId = id;

                // 将当前菜谱转换成系统菜谱
                if (!string.IsNullOrEmpty(Request.QueryString["action"]) && Request.QueryString["action"] == "view")
                {
                    cat.RecipeId = logic.recipe.insertFromDiyToSystem(cat);
                }
                else
                {
                    logic.recipe.update(cat);
                }

                SaveRecipeItems(cat.RecipeId);
            }
            else
            {
                int recipeId = logic.recipe.insert(cat);
                if (recipeId != 0)
                {
                    SaveRecipeItems(recipeId);
                }
            }

            Library.Script.ClientMsgUrl("保存成功！", "recipeList.aspx");
            #endregion
        }
        // 保存菜谱原料信息
        private void SaveRecipeItems(int recipeId)
        {
            foreach (RepeaterItem item in rptSelectedProduct.Items)
            {
                if (item.ItemType == ListItemType.AlternatingItem || item.ItemType == ListItemType.Item)
                {
                    HiddenField hd = item.FindControl("hdProductId") as HiddenField;
                    if (!string.IsNullOrEmpty(hd.Value))
                    {
                        logic.recipeItem.insert(new RecipeItemEntity() { RecipeId = recipeId, ProductId = Convert.ToInt32(hd.Value) });
                    }
                }
            }
        }
        protected void sm1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e)
        {
            sm1.AsyncPostBackErrorMessage = e.Exception.Message;
        }
    }
    internal class ProductItem
    {
        public int ProductId { get; set; }
        public string ProductName { get; set; }
    }
}
